import { memo, useEffect, useMemo, useState } from "react";
import { Button, Col, Drawer, Row, Spin, Tabs } from "antd";
import { orderTimeColumnsConfig, tabsList } from "./config";
import OrderTimeStyle from "./style";
import { EditableProTable } from "@ant-design/pro-components";
import { ChromeOutlined, RedoOutlined } from "@ant-design/icons";
import {
  useFetch_commitCrouse_service,
  useFetch_getCrouseInfo_service,
} from "../../../../service/course";
import { orderTimeType, propsType, reducibleTimeType } from "../../config";
import classNames from "classnames";

const Order_time = memo((props: propsType) => {
  const { id, open, close } = props;
  const [currentTab, setCurrentTab] = useState("");
  const [orderTime, setOrderTime] = useState<orderTimeType[] | []>([]);
  const [edit, editLoading] = useFetch_commitCrouse_service();
  const [getCourse, getInfoLoading] = useFetch_getCrouseInfo_service();

  useEffect(() => {
    if (id) {
      getCourse(id).then((res: { reducibleTime: orderTimeType[] }) => {
        setOrderTime(res.reducibleTime ?? []);
        setCurrentTab(tabsList[0].key);
      });
    }
  }, [id]);

  const tabData: reducibleTimeType | [] = useMemo(() => {
    const OrderTimeIndex = orderTime.findIndex((item: orderTimeType) => {
      return item.week === currentTab;
    });
    return OrderTimeIndex >= 0
      ? (orderTime[OrderTimeIndex].orderTime as reducibleTimeType)
      : [];
  }, [currentTab, editLoading]);

  const currentWeekIndex = useMemo(() => {
    return orderTime.findIndex((item) => item.week === currentTab);
  }, [currentTab]);

  const tabsChange = (key: string) => {
    setCurrentTab(key);
  };
  const saveOrderTime = (
    row: number,
    data: { index: number; startTime: string; endTime: string; key: number }
  ) => {
    const { index, ...formatData } = data;
    const copyOrderTime = JSON.parse(
      JSON.stringify(orderTime)
    ) as orderTimeType[];

    // 1 新增新日期计划
    if (currentWeekIndex === -1) {
      const newDateOrderTime = [formatData];
      copyOrderTime.push({
        week: currentTab,
        orderTime: newDateOrderTime,
      });
    } else {
      const existOrder: number = orderTime[
        currentWeekIndex
      ].orderTime.findIndex((item) => item.key === row) as number;
      // 2 已有日期新增字段
      if (existOrder === -1) {
        copyOrderTime[currentWeekIndex].orderTime.push(formatData);
      } else {
        // 3 已有日期修改字段
        copyOrderTime[currentWeekIndex].orderTime[existOrder] = formatData;
      }
    }
    setOrderTime(copyOrderTime);
    edit(id!, { reducibleTime: copyOrderTime });
  };

  const onDeleteHandler = (key: number) => {
    const copyOrderTime = JSON.parse(
      JSON.stringify(orderTime)
    ) as orderTimeType[];

    const newOrder = copyOrderTime[currentWeekIndex].orderTime.filter(
      (item) => item.key !== key
    ) as unknown as orderTimeType[];
    if (newOrder.length === 0) copyOrderTime.splice(currentWeekIndex, 1);
    copyOrderTime[currentWeekIndex].orderTime = newOrder;

    setOrderTime(copyOrderTime);
    edit(id!, { reducibleTime: copyOrderTime });
  };

  const syncOrderTime = (tabs: string[]): void => {
    const currentOrderData = (orderTime[currentWeekIndex]?.orderTime ?? []) as
      | reducibleTimeType[]
      | [];
    const newData = tabs.map((item) => ({
      orderTime: currentOrderData,
      week: item,
    })) as orderTimeType[];
    setOrderTime(newData);
    edit(id!, { reducibleTime: newData });
  };

  const allWorkDaySyncClick = () => {
    const tabs = ["monday", "tuesday", "wednesday", "thursday", "friday"];
    syncOrderTime(tabs);
  };
  const allWeekSyncClick = () => {
    const tabs = [
      "monday",
      "tuesday",
      "wednesday",
      "thursday",
      "friday",
      "saturday",
      "sunday",
    ];
    syncOrderTime(tabs);
  };

  return (
    <Drawer
      onClose={() => close(false)}
      open={open}
      title="可约时间"
      width="50vw"
    >
      <OrderTimeStyle>
        <Spin spinning={getInfoLoading as boolean}>
          <Tabs
            onChange={tabsChange}
            type="card"
            activeKey={currentTab}
            items={tabsList}
          />
          <EditableProTable
            headerTitle={<span>当前预约日期 {currentTab}</span>}
            rowKey="key"
            editable={{
              onSave(
                row: number,
                data: {
                  startTime: string;
                  endTime: string;
                  key: number;
                  index: number;
                }
              ) {
                saveOrderTime(row, data);
              },
              actionRender: (_row, _config, dom) => [dom.save, dom.cancel],
            }}
            recordCreatorProps={{
              position: "bottom",
              record: (index: number) => ({
                key: index + 1,
                // getMaxKey(
                //   orderTime.filter((item) => item.week === currentTab)[0] ??
                //     []
                // ) + 1,
              }),
            }}
            value={tabData}
            columns={orderTimeColumnsConfig(onDeleteHandler)}
          />
          <Row>
            <Col span={12} style={{ textAlign: "center" }}>
              <Button
                type={"primary"}
                icon={<RedoOutlined />}
                style={{ width: "90%" }}
                onClick={allWorkDaySyncClick}
                className={classNames({
                  btnDisabled:
                    currentTab === "sunday" || currentTab === "saturday",
                })}
              >
                全工作日同步
              </Button>
            </Col>
            <Col span={12} style={{ textAlign: "center" }}>
              <Button
                danger
                icon={<ChromeOutlined />}
                style={{ width: "90%" }}
                type={"primary"}
                onClick={allWeekSyncClick}
              >
                每周同步
              </Button>
            </Col>
          </Row>
        </Spin>
      </OrderTimeStyle>
    </Drawer>
  );
});

export default Order_time;
